<template>
  <div class="dictionary-container">
    <!-- 标题和操作区 -->
    <div class="header-section">
      <h1 class="text-2xl font-bold mb-4">字典对照</h1>
      
      <div class="operation-bar flex flex-wrap gap-4 items-center">
        <!-- 搜索框 -->
        <el-input
          v-model="searchKeyword"
          placeholder="搜索词汇..."
          prefix-icon="Search"
          class="search-input w-64"
          @keyup.enter="handleSearch"
        />
        
        <!-- 字典选择器 -->
        <div class="dictionary-selectors flex gap-2">
          <el-select
            v-model="selectedDict1"
            placeholder="选择第一个字典"
            class="w-40"
            @change="loadDictionaryData"
          >
            <el-option
              v-for="dict in dictionaries"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
          
          <el-select
            v-model="selectedDict2"
            placeholder="选择第二个字典"
            class="w-40"
            @change="loadDictionaryData"
          >
            <el-option
              v-for="dict in dictionaries"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </div>
        
        <!-- 刷新按钮 -->
        <el-button 
          icon="Refresh" 
          @click="refreshData"
          class="ml-auto"
        >
          刷新
        </el-button>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <el-skeleton v-if="loading" class="mb-4" :rows="5" />
    
    <!-- 字典对照表格 -->
    <el-table
      v-else-if="dictItems.length > 0"
      :data="filteredItems"
      border
      stripe
      class="mt-4"
      :header-cell-style="{ 'background-color': '#f5f7fa' }"
    >
      <el-table-column
        prop="word"
        label="词汇"
        width="180"
        :cell-style="{ 'font-weight': 'bold' }"
      />
      
      <el-table-column
        label="字典 1: {{ getDictName(selectedDict1) }}"
        min-width="300"
      >
        <template #default="scope">
          <div v-if="scope.row.dict1Definition" class="definition-content">
            {{ scope.row.dict1Definition }}
          </div>
          <div v-else class="text-gray-400 italic">无定义</div>
        </template>
      </el-table-column>
      
      <el-table-column
        label="字典 2: {{ getDictName(selectedDict2) }}"
        min-width="300"
      >
        <template #default="scope">
          <div v-if="scope.row.dict2Definition" class="definition-content">
            {{ scope.row.dict2Definition }}
          </div>
          <div v-else class="text-gray-400 italic">无定义</div>
        </template>
      </el-table-column>
      
      <el-table-column
        label="操作"
        width="120"
      >
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            @click="showDetails(scope.row)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty
        description="请选择字典并加载数据"
      />
    </div>
    
    <!-- 分页 -->
    <div v-if="dictItems.length > 0" class="pagination mt-4">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="filteredItems.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
      />
    </div>
    
    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`${currentDetailItem?.word || ''} 详情`"
      :width="dialogWidth"
    >
      <div v-if="currentDetailItem" class="detail-content">
        <div class="detail-section">
          <h3 class="text-lg font-semibold mb-2">
            字典 1: {{ getDictName(selectedDict1) }}
          </h3>
          <div v-if="currentDetailItem.dict1Definition" class="definition-text">
            {{ currentDetailItem.dict1Definition }}
          </div>
          <div v-else class="text-gray-400 italic">无定义</div>
        </div>
        
        <div class="detail-section mt-4">
          <h3 class="text-lg font-semibold mb-2">
            字典 2: {{ getDictName(selectedDict2) }}
          </h3>
          <div v-if="currentDetailItem.dict2Definition" class="definition-text">
            {{ currentDetailItem.dict2Definition }}
          </div>
          <div v-else class="text-gray-400 italic">无定义</div>
        </div>
        
        <div v-if="currentDetailItem.synonyms && currentDetailItem.synonyms.length" class="detail-section mt-4">
          <h3 class="text-lg font-semibold mb-2">同义词</h3>
          <el-tag
            v-for="synonym in currentDetailItem.synonyms"
            :key="synonym"
            class="mr-2 mb-2"
          >
            {{ synonym }}
          </el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';

// 定义字典类型
interface Dictionary {
  id: string;
  name: string;
  description: string;
}

// 定义字典条目类型
interface DictionaryItem {
  word: string;
  dict1Definition?: string;
  dict2Definition?: string;
  synonyms?: string[];
  partOfSpeech?: string;
}

// 模拟字典数据
const dictionaries: Dictionary[] = [
  { id: 'dict1', name: '现代汉语词典', description: '现代汉语规范词典' },
  { id: 'dict2', name: '牛津高阶英汉双解词典', description: '权威英语学习词典' },
  { id: 'dict3', name: '古代汉语词典', description: '古代汉语词汇查询' },
  { id: 'dict4', name: '成语大词典', description: '收录常用成语解释' }
];

// 状态管理
const selectedDict1 = ref<string>('dict1');
const selectedDict2 = ref<string>('dict2');
const searchKeyword = ref<string>('');
const loading = ref<boolean>(false);
const dictItems = ref<DictionaryItem[]>([]);
const currentPage = ref<number>(1);
const pageSize = ref<number>(10);
const detailDialogVisible = ref<boolean>(false);
const currentDetailItem = ref<DictionaryItem | null>(null);
const dialogWidth = ref<string>('60%');

// 获取字典名称
const getDictName = (dictId: string): string => {
  const dict = dictionaries.find(d => d.id === dictId);
  return dict ? dict.name : '';
};

// 模拟加载字典数据
const loadDictionaryData = () => {
  if (!selectedDict1.value || !selectedDict2.value) return;
  
  loading.value = true;
  
  // 模拟API请求延迟
  setTimeout(() => {
    // 生成模拟数据
    const generateMockData = (): DictionaryItem[] => {
      const words = [
        '计算机', '程序', '算法', '数据', '结构', '网络', '系统', '软件', '硬件', '数据库',
        '人工智能', '机器学习', '深度学习', '神经网络', '自然语言处理', '图像识别', '大数据',
        '云计算', '区块链', '加密', '安全', '漏洞', '测试', '开发', '部署', '迭代', '版本',
        '接口', '框架', '库', '工具', '语言', '编译', '解释', '调试', '优化', '性能', '并发'
      ];
      
      return words.map(word => ({
        word,
        dict1Definition: `${word} - ${getDictName(selectedDict1.value)}中的解释：这是一个关于${word}的详细解释，包含其含义、用法和相关示例。`,
        dict2Definition: `${word} - ${getDictName(selectedDict2.value)}中的解释：提供了${word}的另一种解释角度，可能包含不同的侧重点和应用场景。`,
        synonyms: [word + '1', word + '2', word + '3'].slice(0, Math.floor(Math.random() * 3) + 1),
        partOfSpeech: ['名词', '动词', '形容词'][Math.floor(Math.random() * 3)]
      }));
    };
    
    dictItems.value = generateMockData();
    currentPage.value = 1; // 重置到第一页
    loading.value = false;
  }, 800);
};

// 刷新数据
const refreshData = () => {
  loadDictionaryData();
  ElMessage.success('数据已刷新');
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置到第一页
};

// 筛选后的条目
const filteredItems = computed<DictionaryItem[]>(() => {
  if (!searchKeyword.value) {
    return dictItems.value;
  }
  
  const keyword = searchKeyword.value.toLowerCase();
  return dictItems.value.filter(item => 
    item.word.toLowerCase().includes(keyword) ||
    (item.dict1Definition && item.dict1Definition.toLowerCase().includes(keyword)) ||
    (item.dict2Definition && item.dict2Definition.toLowerCase().includes(keyword))
  );
});

// 分页处理
const paginatedItems = computed<DictionaryItem[]>(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return filteredItems.value.slice(startIndex, startIndex + pageSize.value);
});

// 处理页码大小变化
const handlePageSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
};

// 处理页码变化
const handleCurrentPageChange = (page: number) => {
  currentPage.value = page;
};

// 显示详情
const showDetails = (item: DictionaryItem) => {
  currentDetailItem.value = item;
  detailDialogVisible.value = true;
};

// 监听窗口大小变化，调整弹窗宽度
const handleResize = () => {
  dialogWidth.value = window.innerWidth < 768 ? '90%' : '60%';
};

// 初始化
onMounted(() => {
  loadDictionaryData();
  window.addEventListener('resize', handleResize);
  handleResize(); // 初始设置
});

// 清理事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});

// 监听字典选择变化
watch([selectedDict1, selectedDict2], () => {
  if (selectedDict1.value && selectedDict2.value) {
    loadDictionaryData();
  }
});
</script>

<style scoped>
.dictionary-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.operation-bar {
  margin-bottom: 20px;
}

.empty-state {
  margin: 40px 0;
  text-align: center;
}

.pagination {
  text-align: right;
}

.detail-content {
  line-height: 1.8;
}

.detail-section {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.detail-section:last-child {
  border-bottom: none;
}

.definition-content {
  line-height: 1.6;
  word-break: break-word;
}

.definition-text {
  line-height: 1.8;
  text-align: justify;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    width: 100% !important;
  }
  
  .dictionary-selectors {
    width: 100%;
    flex-direction: column;
  }
  
  .dictionary-selectors .el-select {
    width: 100% !important;
  }
}
</style>
